package com.fastloan.mgt.product.temp.service.impl;

import com.fastloan.common.BasicServiceImpl;
import com.fastloan.mgt.product.temp.dao.DefTempMapper;
import com.fastloan.mgt.product.temp.model.DefTemp;
import com.fastloan.mgt.product.temp.model.DefTempOpt;
import com.fastloan.mgt.product.temp.model.vo.DefTempDTO;
import com.fastloan.mgt.product.temp.model.vo.DefTempVO;
import com.fastloan.mgt.product.temp.service.DefTempOptService;
import com.fastloan.mgt.product.temp.service.DefTempService;
import com.fastloan.utils.DozerUtil;
import com.kawins.supers.tree.Bean2TreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.beans.Transient;
import java.util.List;

import static com.fastloan.mgt.product.enums.ProductEnum.UNPUBLISHED;
import static java.util.stream.Collectors.toList;

/**
 * @author admins
 * createTime 2017/11/07
 */
@Service
public class DefTempServiceImpl extends BasicServiceImpl<DefTemp> implements DefTempService {
    @Autowired
    private DefTempMapper defTempMapper;

    @Autowired
    private DefTempOptService defTempOptService;

    @Override
    public List<DefTempVO> queryDefTemp(String productId) {
        Bean2TreeUtil<DefTempVO> treeUtil = new Bean2TreeUtil<>();
        List<DefTempVO> defTempVOS = defTempMapper.queryDefTemp(productId);
        return getDefTempVOS(treeUtil, defTempVOS);

    }

    @Override
    @Transient
    public void insertTemp(List<DefTempDTO> tempDTOList) {
        tempDTOList.forEach(defTempDTO -> {
            DefTemp defTemp = DozerUtil.map(defTempDTO, DefTemp.class);
            insertSelective(defTemp);
            defTempDTO.getDefTempOptList()
                    .forEach(tempOpt -> {
                        DefTempOpt defTempOpt = DozerUtil.map(tempOpt, DefTempOpt.class);
                        defTempOptService.insertSelective(defTempOpt);
                    });
        });
    }

    @Override
    public List<DefTempVO> queryAllTemp() {
        Bean2TreeUtil<DefTempVO> treeUtil = new Bean2TreeUtil<>();
        List<DefTemp> defTemps = selectAll();
        List<DefTempVO> defTempVOS = defTemps.parallelStream()
                .map(defTemp -> DozerUtil.map(defTemp, DefTempVO.class)).collect(toList());
        return getDefTempVOS(treeUtil, defTempVOS);
    }

    private List<DefTempVO> getDefTempVOS(Bean2TreeUtil<DefTempVO> treeUtil, List<DefTempVO> defTempVOS) {
        List<DefTempVO> defTempVOList = defTempVOS.stream().peek(defTempVO -> {
            if (!StringUtils.isBlank(defTempVO.getProductId())) {
                defTempVO.setIfSave(true);
            }
        }).collect(toList());
        return treeUtil.getChildNodesByParentId(defTempVOList, 0);
    }
}
